package com.lagou.util;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class EmailUtils {

    public static void sendEmail(String mailHost, String mailFrom, String passwordMailFrom, String mailTo, String mailTitle, String mailContent)
            throws MessagingException {
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.host", mailHost);
        properties.setProperty("mail.smtp.auth", "true");

        Session session = Session.getInstance(properties);
        session.setDebug(true);

        Transport transport = session.getTransport();
        transport.connect(mailHost, mailFrom, passwordMailFrom);

        Message textMail = createTextMail(session, mailFrom, mailTo, mailTitle, mailContent);
        transport.sendMessage(textMail, textMail.getAllRecipients());
        transport.close();
    }

    public static MimeMessage createTextMail(Session session, String mailFrom, String mailTo, String mailTitle, String mailContent)
            throws MessagingException {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(mailFrom));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
        message.setSubject(mailTitle);
        message.setContent(mailContent, "text/html;charset=UTF-8");
        return message;
    }
}
